import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../controllers/auth_controller.dart';
import '../../../routes/app_routes.dart';

/// 首页控制器
class HomeController extends GetxController {
  // 注入依赖
  final AuthController _authController = Get.find<AuthController>();
  
  // 底部导航栏选中索引
  final RxInt _selectedIndex = 0.obs;
  int get selectedIndex => _selectedIndex.value;
  
  // 加载状态
  final RxBool _isLoading = false.obs;
  bool get isLoading => _isLoading.value;
  
  // 用户信息
  final RxString _userName = 'Admin'.obs;
  String get userName => _userName.value;
  
  final RxString _userEmail = 'admin@example.com'.obs;
  String get userEmail => _userEmail.value;
  
  String get userInitials {
    if (_userName.value.isNotEmpty) {
      return _userName.value.substring(0, 1).toUpperCase();
    }
    return 'A';
  }
  
  // 上次登录时间
  final RxString _lastLoginTime = '2023-05-27 08:30'.obs;
  String get lastLoginTime => _lastLoginTime.value;
  
  // 设备数量统计
  final RxInt _onlineDeviceCount = 12.obs;
  int get onlineDeviceCount => _onlineDeviceCount.value;
  
  final RxInt _offlineDeviceCount = 3.obs;
  int get offlineDeviceCount => _offlineDeviceCount.value;
  
  final RxInt _alertDeviceCount = 2.obs;
  int get alertDeviceCount => _alertDeviceCount.value;
  
  final RxInt _faultDeviceCount = 1.obs;
  int get faultDeviceCount => _faultDeviceCount.value;
  
  // 设备列表
  final RxList<Map<String, dynamic>> _devices = <Map<String, dynamic>>[].obs;
  List<Map<String, dynamic>> get devices => _devices;
  
  // 场景列表
  final RxList<Map<String, dynamic>> _scenes = <Map<String, dynamic>>[].obs;
  List<Map<String, dynamic>> get scenes => _scenes;
  
  // 最近活动
  final RxList<Map<String, dynamic>> _recentActivities = <Map<String, dynamic>>[].obs;
  List<Map<String, dynamic>> get recentActivities => _recentActivities;
  
  @override
  void onInit() {
    super.onInit();
    _loadUserInfo();
    _loadDevices();
    _loadScenes();
    _loadActivities();
  }
  
  /// 加载用户信息
  void _loadUserInfo() {
    _userName.value = _authController.userName;
    _userEmail.value = _authController.userEmail;
    _lastLoginTime.value = _authController.lastLoginTime;
  }
  
  /// 加载设备数据
  Future<void> _loadDevices() async {
    _isLoading.value = true;
    
    try {
      // 模拟API请求
      await Future.delayed(const Duration(seconds: 1));
      
      // 示例数据
      _devices.value = [
        {
          'id': '1',
          'name': '客厅温湿度传感器',
          'type': 'temperatureSensor',
          'status': '在线',
          'location': '客厅',
          'value': '26℃',
        },
        {
          'id': '2',
          'name': '卧室空气质量传感器',
          'type': 'airQualitySensor',
          'status': '在线',
          'location': '卧室',
          'value': '优',
        },
        {
          'id': '3',
          'name': '厨房烟雾传感器',
          'type': 'smokeSensor',
          'status': '离线',
          'location': '厨房',
          'value': '--',
        },
        {
          'id': '4',
          'name': '客厅智能灯',
          'type': 'smartLight',
          'status': '在线',
          'location': '客厅',
          'value': '开',
        },
        {
          'id': '5',
          'name': '卧室智能窗帘',
          'type': 'smartCurtain',
          'status': '告警',
          'location': '卧室',
          'value': '异常',
        },
      ];
      
      _onlineDeviceCount.value = 3;
      _offlineDeviceCount.value = 1;
      _alertDeviceCount.value = 1;
      _faultDeviceCount.value = 0;
      
    } catch (e) {
      debugPrint('加载设备数据出错: $e');
    } finally {
      _isLoading.value = false;
    }
  }
  
  /// 加载场景数据
  Future<void> _loadScenes() async {
    _isLoading.value = true;
    
    try {
      // 模拟API请求
      await Future.delayed(const Duration(seconds: 1));
      
      // 示例数据
      _scenes.value = [
        {
          'id': '1',
          'name': '回家模式',
          'type': 'home',
          'deviceCount': 4,
        },
        {
          'id': '2',
          'name': '离家模式',
          'type': 'away',
          'deviceCount': 5,
        },
        {
          'id': '3',
          'name': '睡眠模式',
          'type': 'sleep',
          'deviceCount': 3,
        },
        {
          'id': '4',
          'name': '影院模式',
          'type': 'movie',
          'deviceCount': 2,
        },
      ];
      
    } catch (e) {
      debugPrint('加载场景数据出错: $e');
    } finally {
      _isLoading.value = false;
    }
  }
  
  /// 加载活动数据
  Future<void> _loadActivities() async {
    _isLoading.value = true;
    
    try {
      // 模拟API请求
      await Future.delayed(const Duration(seconds: 1));
      
      // 示例数据
      _recentActivities.value = [
        {
          'icon': Icons.lightbulb,
          'title': '客厅智能灯已开启',
          'time': '10分钟前',
          'isAlert': false,
        },
        {
          'icon': Icons.warning,
          'title': '卧室智能窗帘异常',
          'time': '30分钟前',
          'isAlert': true,
        },
        {
          'icon': Icons.thermostat,
          'title': '温度传感器数据更新',
          'time': '1小时前',
          'isAlert': false,
        },
        {
          'icon': Icons.auto_awesome,
          'title': '回家模式已激活',
          'time': '3小时前',
          'isAlert': false,
        },
      ];
      
    } catch (e) {
      debugPrint('加载活动数据出错: $e');
    } finally {
      _isLoading.value = false;
    }
  }
  
  /// 切换底部导航栏索引
  void changeBottomNavIndex(int index) {
    _selectedIndex.value = index;
  }
  
  /// 导航到通知页面
  void navigateToNotifications() {
    Get.toNamed(AppRoutes.NOTIFICATION);
  }
  
  /// 导航到设置页面
  void navigateToSettings() {
    Get.back();
    Get.toNamed(AppRoutes.SETTINGS);
  }
  
  /// 导航到帮助页面
  void navigateToHelp() {
    Get.back();
    Get.snackbar(
      '提示',
      '帮助与反馈功能正在开发中',
      snackPosition: SnackPosition.BOTTOM,
    );
  }
  
  /// 添加新设备
  void addNewDevice() {
    if (selectedIndex == 1) {
      // 在设备页面
      Get.toNamed(AppRoutes.DEVICE_ADD);
    } else {
      // 不在设备页面，先切换到设备页面
      changeBottomNavIndex(1);
      Future.delayed(const Duration(milliseconds: 300), () {
        Get.toNamed(AppRoutes.DEVICE_ADD);
      });
    }
  }
  
  /// 打开设备详情
  void openDeviceDetail(String deviceId) {
    Get.toNamed('${AppRoutes.DEVICE_DETAIL}/$deviceId');
  }
  
  /// 激活场景
  void activateScene(String sceneId) {
    Get.snackbar(
      '成功',
      '场景已激活',
      snackPosition: SnackPosition.BOTTOM,
    );
  }
  
  /// 退出登录
  void logout() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认退出'),
        content: const Text('您确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              _authController.logout();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  /// 获取设备图标
  IconData getDeviceIcon(String type) {
    switch (type) {
      case 'temperatureSensor':
        return Icons.thermostat;
      case 'humiditySensor':
        return Icons.water_drop;
      case 'airQualitySensor':
        return Icons.air;
      case 'smokeSensor':
        return Icons.smoke_free;
      case 'smartLight':
        return Icons.lightbulb;
      case 'smartCurtain':
        return Icons.curtains;
      default:
        return Icons.devices_other;
    }
  }
  
  /// 获取场景图标
  IconData getSceneIcon(String type) {
    switch (type) {
      case 'home':
        return Icons.home;
      case 'away':
        return Icons.exit_to_app;
      case 'sleep':
        return Icons.nightlight_round;
      case 'movie':
        return Icons.movie;
      default:
        return Icons.auto_awesome;
    }
  }
  
  /// 获取设备状态颜色
  Color getDeviceStatusColor(String status) {
    switch (status) {
      case '在线':
        return Colors.green;
      case '离线':
        return Colors.grey;
      case '告警':
        return Colors.orange;
      case '故障':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }
} 